const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin');

const commonCssLoader = [
  MiniCssExtractPlugin.loader,
  'css-loader',
  {
    loader: 'postcss-loader',
    options: {
      postcssOptions: {
        plugins: ['postcss-preset-env'],
      },
    },
  },
];

module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/index.[contenthash:10].js',
    path: resolve(__dirname, 'build'),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        enforce: 'pre',
        exclude: /node_modules/,
        use: [
          {
            loader: 'eslint-loader',
            options: {
              fixe: true,
            },
          },
        ],
      },
      {
        oneOf: [
          {
            test: /\.css$/,
            use: [...commonCssLoader],
          },
          {
            test: /\.less$/,
            use: [...commonCssLoader, 'less-loader'],
          },
          {
            test: /\.(sass|scss)$/,
            use: [...commonCssLoader, 'sass-loader'],
          },
          {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            options: {
              presets: [
                [
                  '@babel/preset-env',
                  {
                    targets: {
                      ie: 10,
                      edge: 17,
                      firefox: 60,
                      chrome: 60,
                      safari: 10,
                    },
                    useBuiltIns: 'usage',
                    corejs: 3,
                  },
                ],
              ],
              cacheDirectory: true,
            },
          },
          {
            test: /\.(jpg|jpeg|png|gif)$/,
            loader: 'url-loader',
            options: {
              esModule: false,
              outputPath: 'image',
              limit: 10 * 1024,
              name: '[hash:8].[ext]',
            },
          },
          {
            test: /\.html$/,
            loader: 'html-withimg-loader',
          },
          {
            exclude: /\.(html|js|css|less|sass|scss|jpg|jpeg|png|gif)$/,
            loader: 'file-loader',
            options: {
              outputPath: 'media',
              name: '[hash:10].[ext]',
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      minify: {
        collapseWhitespace: true,
        removeComments: true,
      },
    }),
    new MiniCssExtractPlugin({
      filename: 'css/main[contenthash:10].css',
    }),
    new CssMinimizerWebpackPlugin(),
  ],
  mode: 'production',
};
